/*
 * Copyright (c) 2015 Minshenglife. All rights reserved. Minshenglife
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.sentry.commons.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.UUID;


/**
 * 随机数工具
 * 
 * @author WuBo (wub1@minshenglife.com)
 * 
 */
public final class Randoms {

    private static final SecureRandom RANDOM = new SecureRandom();

    private static final String DEV_URANDOM = "/dev/urandom";


    private Randoms() {}

    /**
     * linux系统下读取/dev/urandom来实现的随机数，windows下则使用JDK的方式
     * 
     * @return
     */
    public static byte[] urandom(int num) {
        byte[] bs = null;
        if (System.getProperty("os.name").equalsIgnoreCase("linux")) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(DEV_URANDOM);
                bs = new byte[num];
                fis.read(bs, 0, num);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            RANDOM.nextBytes(bs);
        }
        return bs;
    }

    /**
     * 将数字头部以0补全到足够位数
     * 
     * @param number
     * @param len 补全后的长度
     * @return
     */
    public static String prettyNum(int number, int len) {
        String numss = String.valueOf(Math.abs(number));
        int numlen = numss.length();
        if (numlen >= len) {
            return numss;
        }

        String rs = "";
        int i = len - numlen;
        while (i-- > 0) {
            rs += "0";
        }


        return rs + numss;
    }



    /**
     * Type 4 的uuid格式 ,例如：f0a8a013-e3a3-4457-bcbd-3cec40952e53
     */
    public static String uuid() {
        return UUID.randomUUID().toString();
    }

    /**
     * Type 4 的uuid格式 {@link #uuid} , 中间无-分割.
     */
    public static String uuid2() {
        return uuid().replaceAll("-", "");
    }

    /**
     * 使用SecureRandom随机生成Long.
     */
    public static long randomLong() {
        return Math.abs(RANDOM.nextLong());
    }


}
